<template>
	<view class="main">
		<view :class="headerClass()">
			<img :src="getLogo()" :class="logoClass()" alt="" />
			<img
				v-if="version === 'main'"
				class="bottom-img"
				:src="aboutLogo"
				@longpress="handleLongPress"
				alt="" />
		</view>
		<view class="form">
			<up-form labelPosition="left" :model="loginModel" ref="form">
				<up-form-item
					prop="phone"
					:borderBottom="true"
					class="form-item"
					ref="item1">
					<up-input
						v-model="loginModel.phone"
						:placeholder="t('login.phone')"
						border="none"
						@change="changeInput(1, $event)"></up-input>
				</up-form-item>
				<up-form-item
					prop="password"
					:borderBottom="true"
					ref="item2"
					class="form-item">
					<up-input
						v-model="loginModel.password"
						:placeholder="t('login.pwd')"
						:password="!isPasswordVisible"
						@change="changeInput(2, $event)"
						border="none">
						<template #suffix>
							<img
								class="loginInputIcon"
								:src="isPasswordVisible ? eyePic : closePic"
								alt=""
								@click="
									isPasswordVisible = !isPasswordVisible
								" />
						</template>
					</up-input>
				</up-form-item>
				<up-form-item
					prop="password"
					ref="item3"
					class="form-item checkbox">
					<up-checkbox
						:customStyle="{ marginBottom: '8px' }"
						:label="t('login.rememberPwd')"
						name="remember"
						activeColor="#fff"
						iconColor="rgb(0, 122, 255)"
						usedAlone
						labelColor="rgba(0, 0, 0, 0.4)"
						v-model:checked="loginModel.remember"></up-checkbox>
				</up-form-item>
			</up-form>

			<up-button
				:text="t('login.Btn')"
				:options="{ styleIsolation: 'shared' }"
				color="#4e6fff"
				:disabled="isAbleLogin"
				@click="submit"
				class="button"></up-button>
		</view>
		<!-- 底部隐私政策 -->
		<view v-if="version === 'main'" class="login-bottom">
			<up-form :model="loginBottom" ref="loginBottom" class="bottom-form">
				<up-form-item prop="read" ref="item3">
					<up-checkbox
						shape="circle"
						name="read"
						activeColor="#fff"
						iconColor="rgb(0, 122, 255)"
						usedAlone
						labelColor="rgba(0, 0, 0, 0.4)"
						@change="changeRead($event)"
						v-model:checked="loginBottom.read"></up-checkbox>
					<text>{{ t("login.info.agree") }}</text>
					<up-text
						:text="t('login.info.service')"
						@click="
							navigateTo(
								'/pages/tabs/mine/externalLink/index?type=1'
							)
						"></up-text>
					<text>{{ t("login.info.and") }}</text>
					<up-text
						:text="t('login.info.privacy')"
						@click="
							navigateTo(
								'/pages/tabs/mine/externalLink/index?type=2'
							)
						"></up-text>
				</up-form-item>
			</up-form>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, reactive, onBeforeMount } from "vue";
import { useI18n } from "vue-i18n";
import { userLogin } from "@/service/index";
const instance: any = getCurrentInstance();
const version: any = instance?.proxy?.$appVersion;
const isPasswordVisible = ref(false);
import { getPlatformDefaultId, safeGetPushId } from "@/utils/push";
const isAbleLogin = ref(true);
const longPressTimer = ref<number>(0);
const longPressInterval = ref<ReturnType<typeof setInterval> | null>(null);
const isTestEnv = useUniversalStorage("TEST_URL", null as any);
const loginModel = reactive({
	phone: "",
	password: "",
	remember: false,
});
const loginBottom = reactive({
	read: false,
});
const aboutLogo = resolveStaticPath("image/mine/login/aboutLogo.png");
const eyePic = resolveStaticPath("image/mine/login/eye.png");
const closePic = resolveStaticPath("image/mine/login/close-eye.png");
// 国际化
const { locale, t } = useI18n();

const rememberStore: any = useUniversalStorage("remember", {
	phone: "",
	password: "",
});
onBeforeMount(() => {
	if (rememberStore.value.phone) {
		loginModel.phone = rememberStore.value.phone;
		loginModel.password = rememberStore.value.password;
		loginModel.remember = true;
		loginBottom.read = true;
		isAbleLogin.value = false;
	}
});
const navigateTo = (url: string) => {
	console.log(url);
	uni.navigateTo({
		url: url,
	});
};
const getLogo = () => {
	switch (version) {
		case "main":
			return resolveStaticPath("image/mine/login/login_logo.png");
		case "xz":
			return resolveStaticPath("image/mine/login/login_xz.png");
		case "sin":
			return resolveStaticPath("image/mine/login/login_sin.png");
		case "nojt":
			return resolveStaticPath("image/mine/login/login_nojt.png");
		case "pujin":
			return resolveStaticPath("image/mine/login/login_pujin.png");
		default:
			return resolveStaticPath("image/mine/login/login_logo.png");
	}
};
const logoClass = () => {
	switch (version) {
		case "main":
			return "logo-main";
		case "sin":
			return "logo_sin";
		default:
			return "logo-other";
	}
};
const changeRead = (e: boolean) => {
	loginBottom.read = e;
};
const headerClass = () => {
	switch (version) {
		case "main":
			return "header";
		case "sin":
			return "header-sin";
		default:
			return "header-other";
	}
};
const handleTouchEnd = () => {
	if (longPressInterval.value) {
		clearInterval(longPressInterval.value);
		longPressInterval.value = null;
	}
	longPressTimer.value = 0;
	document.removeEventListener("touchend", handleTouchEnd);
};
// 类型定义
type LongPressHandler = () => void;
// 长按处理逻辑
const handleLongPress: LongPressHandler = () => {
	longPressTimer.value = 0;
	if (longPressInterval.value) {
		clearInterval(longPressInterval.value);
	}
	longPressInterval.value = setInterval(() => {
		longPressTimer.value++;
		if (longPressTimer.value >= 2) {
			toggleBaseUrl();
			if (longPressInterval.value) {
				clearInterval(longPressInterval.value);
			}
			longPressTimer.value = 0;
		}
	}, 1000);

	// 添加触摸结束监听
	document.addEventListener("touchend", handleTouchEnd);
};

const toggleBaseUrl = () => {
	const TEST_URL = "https://paas-test.jtcx.cn/api/v1/";
	console.log(isTestEnv.vlaue);
	// 切换环境存储状态
	if (isTestEnv.value) {
		isTestEnv.value = null;
	} else {
		isTestEnv.value = JSON.stringify(TEST_URL);
	}
	uni.showToast({
		title: `已切换到${isTestEnv.value ? "测试" : "正式"}环境`,
		icon: "none",
		duration: 2000,
	});
	setTimeout(() => {
		uni.showModal({
			title: "提示",
			content: "环境已切换，如账号密码不同，需重新登录",
			showCancel: false,
			success: () => {
				// #ifdef APP-PLUS
				plus.runtime.restart();
				// #endif
				// #ifdef H5
				location.reload();
				// #endif
			},
		});
	}, 1000);
};
const changeInput = (index: number, value: any) => {
	if (index == 1) {
		loginModel.phone = value;
	} else {
		loginModel.password = value;
	}
	if (loginModel.password.length >= 1 && loginModel.phone.length >= 1) {
		isAbleLogin.value = false;
	} else {
		isAbleLogin.value = true;
	}
};
const submit = () => {
	if (version === "main" && !loginBottom.read) {
		instance.proxy.$message(t("login.form.agreement"), "warning");
		return;
	}
	goLogin();
};
const goLogin = async () => {
	try {
		// 响应式数据
		const query = {
			phone: loginModel.phone,
			password: loginModel.password,
			language: locale.value === "zh-Hans" ? "zh" : "en",
			unipush_cid: "",
		};
		// #ifdef APP-PLUS
		if (version !== "xz") {
			let pinf = plus.push.getClientInfo();
			if (pinf.clientid) {
				query.unipush_cid = pinf.clientid;
			}
		}
		// #endif
		const res = await userLogin(query);
		console.log(res);
		if (res.data.code === 0) {
			// 记住密码处理
			if (loginModel.remember) {
				rememberStore.value = {
					phone: loginModel.phone,
					password: loginModel.password,
				};
			} else {
				rememberStore.value = null;
			}

			// 用户信息处理
			const userData = res.data.data;
			const params = {
				username:
					userData.name ||
					`${t("login.superSweep")}${userData.phone.slice(-4)}`,
				phone: userData.phone,
				staff_id: userData.staff_id,
				customer_type: userData.customer_type,
			};
			// 存储数据
			const userInfoStore = useUniversalStorage("userinfo", {
				username: "",
				phone: "",
				staff_id: "",
				customer_type: "", //用户分类0未分类1终端客户2代理
			});
			userInfoStore.value = params;
			const tokenStore = useUniversalStorage("token", "");
			tokenStore.value = userData.token;
			// 跳转首页
			uni.switchTab({
				url: "/pages/index/index",
			});
		} else {
			instance.proxy.$message(res.data.msg, "error");
		}
	} catch (error) {
		console.error("登录失败:", error);
	}
};
</script>

<style lang="scss" scoped>
.header {
	text-align: left;
	padding: 140rpx 40rpx 30rpx;
}
.main {
	position: relative;
	height: 100vh;
	background: linear-gradient(
		215deg,
		rgba(223, 223, 253, 0.5) 0%,
		rgba(249, 250, 254, 0.5) 100%
	);

	.header-sin {
		text-align: center;
		padding: 250rpx 40rpx 150rpx;
	}

	.header-other {
		text-align: center;
		padding: 140rpx 40rpx 60rpx;
	}
	img {
		display: block;
	}
	.logo-main {
		width: 156rpx;
	}

	.logo-sin {
		width: 340rpx;
		margin: 0 auto;
	}

	.logo-other {
		width: 264rpx;
		margin: 0 auto;
	}
	.bottom-img {
		margin: 36rpx 0 0;
		width: 460rpx;
	}
	.form {
		margin: 20px;
		:deep(.input-placeholder) {
			color: grey !important;
		}
		:deep(.u-form-item__body) {
			padding: 16rpx 0;
		}
		.form-item {
			line-height: 35px;
			margin-top: 10rpx;
		}
		.button {
			height: 42px;
			line-height: 42px;
			margin-top: 20px;
			letter-spacing: 3px;
		}
		:deep(.u-button__text) {
			font-size: 16px !important;
		}
		.loginInputIcon {
			width: 40rpx;
			height: 40rpx;
		}
	}
	.login-bottom {
		position: absolute;
		bottom: 10px;
		text-align: center;
		width: 100%;
		.bottom-form {
			display: inline-block;
		}
		text {
			font-size: 28rpx;
			color: rgba(0, 0, 0, 0.4);
		}
		:deep(.u-checkbox__icon-wrap--circle) {
			width: 16.8px !important;
			height: 16.8px !important;
		}
		:deep(.u-text__value) {
			color: #00aaff !important;
			text-decoration: none !important;
			font-size: 28rpx !important;
			padding: 0 10rpx;
			white-space: nowrap;
		}
	}
}
:deep(.u-input__content__subfix-password-shower) {
	display: none;
}
</style>
